console.log("########## start ###########")


document.getElementById("titleId").innerText = "常用软件下载";

getSoftwareList()

function getSoftwareList() {
    var url = "/rest/get_soft_list";
    ajaxReq(url, "GET", function (response) {
        var list = JSON.parse(response);
        appendToPage(list);
    })
}
function appendToPage(softList) {
    dom = "<table>"
    column = 3
    row = Math.ceil(softList.length / column);
    for (var i = 0; i < row; i++) {
        dom += "<tr>";
        for(var j = 0;j < column; j++){
            var item = softList[i * column + j];
            if(item){
                dom += "<td><div class='soft-item'><a onclick='downloadSoft(this)' target='" + item + "'>" + item + "</a></div></td>";
            }
        }
        dom += "</tr>";
    }
    dom += "</body>";
    document.getElementById("softwareId").innerHTML = dom;
}

function downloadSoft(that) {
    var softname = that.innerText;
    var downurl = "/rest/download_software"
    var param = {
        name: softname
    }
    ajaxReq(downurl, "POST", function (response) {
        var blob = new Blob([response]);

        var filename = softname
        filename = decodeURI(filename);

        if (window.navigator.msSaveOrOpenBlob) {
            navigator.msSaveBlob(blob, filename);
        } else {
            var csvUrl = URL.createObjectURL(blob);
            var link = document.createElement('a');
            link.href = csvUrl;
            link.download = filename;
            link.click();
        }
    }, JSON.stringify(param))
}

var xmlhttp;

function ajaxReq(url, type, callBack, param) {
    xmlhttp = null;
    if (window.XMLHttpRequest) {// code for all new browsers
        xmlhttp = new XMLHttpRequest();
    }
    else if (window.ActiveXObject) {// code for IE5 and IE6
        xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
    }
    if (xmlhttp != null) {
        xmlhttp.onreadystatechange = state_Change;
        type = type || "GET";
        xmlhttp.open(type, url, true);
        xmlhttp.setRequestHeader("Content-Type", "application/json");
        xmlhttp.send(param);
    }
    else {
        console.error("Your browser does not support XMLHTTP.");
    }

    function state_Change() {
        if (xmlhttp.readyState == 4) {// 4 = "loaded"
            if (xmlhttp.status == 200) {// 200 = OK
                callBack && callBack(xmlhttp.response)
            }
            else {
                console.error("Problem retrieving XML data");
            }
        }
    }
}
